var userService = require('../services/userService');
var messageUtil = require('../common/utils/messageUtil');
var cacheUtil = require('../common/utils/cacheUtil');
var toolUtil = require('../common/utils/toolUtil');
var mysqlUtil = require('../common/utils/mysqlUtil');
var inviteRecord = mongoose.model('invite_score_record');
var fs = require('fs');
var Users = mongoose.model('user');
var async = require('async');
var md5 = require('MD5');
var moment = require('moment');
var userDevice = mongoose.model('user_device_profile');
var userInvitation = mongoose.model('user_invitation');
var backUserService = require('../services/backoffice/backOffice-userService');

/**
 * User sign up a user with the information:
 * userID/email/mobilePhone + password
 * The request content-type should be application/json
 */
exports.registerUser = function (req, res) {
    logger.debug('Registering a user...');
    var input = req.body;
    var clientId = input.clientId;
    if ((input.userName != null || input.email != null || input.mobilePhone != null) && input.userPassword != null && input.verificationCode != null) {
        cacheUtil.cacheGet(input.mobilePhone, function (err, result) {
            if (result != null && result == input.verificationCode) {
                var password = md5(input.userPassword);
                userService.registerService(input.userName, input.email, input.mobilePhone, password, clientId, function (err, user) {
                    if (err) {

                        var message = {
                            "deviceId": req.params.deviceId,
                            "mobilePhone": input.mobilePhone,
                            "password": input.userPassword,
                            "message": '用户名已被注册'
                        };
                        toolUtil.putMessageLoginOrRegisterLogMQ(message);

                        logger.error("Failed to register this user - " + err.message);
                        res.json(messageUtil.composeFailedMessage(req, '用户名已被注册'));
                    } else {
                        logger.debug("Succeeded to register a user! - " + user._id);
                        //获取token并缓冲
                        logger.info(user._id);
                        var token = toolUtil.generateAndCacheToken(user._id);
                        //返回消息
                        var registerUserData = {
                            "_id": user._id,
                            "huanxinUserName": user.huanxinUserName,
                            "token": token,
                            "firstLogin": user._doc.firstLogin,
                            "appSetting": user.appSetting,
                            "userType": user.userType,
                            "vStatus": 0,
                            "auth": [],
                            "authenticationStatus": user.authenticationStatus
                        };
                        //userService.sendWelcomeNewsService(input.mobilePhone, function (err, result) {
                        //    if (err) {
                        //        logger.error('failed to send welcome news' + err.message);
                        //    }
                        //});
                        toolUtil.setUserByToken(token);
                        redisClient.sadd('u:all', user._id);
                        res.json(messageUtil.composeSucceededMessage(req, null, registerUserData));
                    }
                });
            } else {
                var message = {
                    "deviceId": req.params.deviceId,
                    "mobilePhone": input.mobilePhone,
                    "password": input.userPassword,
                    "message": '验证码错误'
                };
                toolUtil.putMessageLoginOrRegisterLogMQ(message);
                logger.error("Failed to register user ! - invalid verification code!");
                res.json(messageUtil.composeFailedMessage(req, '验证码错误'));
            }
        })
    } else {
        logger.error("Failed to register user ! - You have to provide at least userID/email/mobilePhone and also password +  verificationCode for registration...!");
        res.json(messageUtil.composeFailedMessage(req, '请填写手机号、密码或验证码'));
    }
};


exports.bindClientId = function (req, res) {
    var clientId = req.params.clientId;
    var token = req.params.token;

    userService.bindClientIdService(clientId, token, function (err, result) {
        if (err) {
            logger.error('Error happened when bindClientId' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Error happened when bindClientId'));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    })
};


/**
 * User login, The loginId could be userID, email or phone number;
 */
exports.login = function (req, res) {

    var mobilePhone = req.body.mobilePhone;
    var userPassword = req.body.userPassword;
    var clientId = req.body.clientId;

    var password = md5(userPassword);
    logger.debug('Trying to login with ' + mobilePhone);
    userService.loginService(mobilePhone, password, clientId, function (err, results) {
        if (err) {

            var message = {
                "deviceId": req.params.deviceId,
                "mobilePhone": mobilePhone,
                "password": userPassword,
                "message": err.message
            };
            toolUtil.putMessageLoginOrRegisterLogMQ(message);

            logger.error(loginId + ' Exception happened when login to the system...!-' + err.message);
            res.json(messageUtil.composeFailedMessage(req, mobilePhone + ' Exception happened when login to the system...!-' + err.message));
        } else {
            //只要结果集中有一个返回值，则表明有记录，说明用户合法
            if (results[0] != null) {
                if (results[0].frozenOrNot) {
                    res.json(messageUtil.composeFailedMessage(req, '帐号被冻结'));
                } else {
                    var _id = results[0]._id;
                    logger.debug(mobilePhone + ' Logined into the system successfully...!');
                    //获取token并缓冲
                    var token = toolUtil.generateAndCacheToken(_id);
                    var loginUserData = {
                        "_id": _id,
                        "token": token
                    };
                    res.json(messageUtil.composeSucceededMessage(req, 'login into the system successfully...', loginUserData));
                    toolUtil.setUserByToken(token);
                }
            }
            else {
                var message = {
                    "deviceId": req.params.deviceId,
                    "mobilePhone": mobilePhone,
                    "password": userPassword,
                    "message": "invalid loginID or password"
                };
                toolUtil.putMessageLoginOrRegisterLogMQ(message);
                logger.debug(mobilePhone + ' Failed to login to the system,invalid loginID or password...!');
                res.json(messageUtil.composeFailedMessage(req, '用户名或密码错误'));
            }
        }
    })
};

//新接口
exports.appLogin = function (req, res) {
    var mobilePhone = req.body.mobilePhone;
    var userPassword = req.body.userPassword;

    var password = md5(userPassword);
    logger.debug('Trying to login with ' + mobilePhone);
    userService.appLoginService(mobilePhone, password, null, function (err, results) {
        if (err) {

            var message = {
                "deviceId": req.params.deviceId,
                "mobilePhone": mobilePhone,
                "password": userPassword,
                "message": err.message
            };
            logger.error(loginId + ' Exception happened when login to the system...!-' + err.message);
            res.json(messageUtil.composeFailedMessage(req, mobilePhone + ' Exception happened when login to the system...!-' + err.message));
            toolUtil.putMessageLoginOrRegisterLogMQ(message);
        } else {
            //只要结果集中有一个返回值，则表明有记录，说明用户合法
            if (results[0] != null) {
                if (results[0].frozenOrNot) {
                    res.json(messageUtil.composeFailedMessage(req, '帐号被冻结'));
                } else {
                    var _id = results[0]._id;
                    logger.debug(mobilePhone + ' Logined into the system successfully...!');
                    //获取token并缓冲
                    var token = toolUtil.generateAndCacheToken(_id);
                    var data = results[0];
                    data.frozenOrNot = undefined;
                    data._doc['token'] = token;
                    data._doc['auth'] = results[1];
                    data._doc['vStatus'] = results[2];
                    data._doc['isSignIn'] = results[3];
                    res.json(messageUtil.composeSucceededMessage(req, 'login into the system successfully...', data));
                    toolUtil.setUserByToken(token);
                }
            } else {
                var message = {
                    "deviceId": req.params.deviceId,
                    "mobilePhone": mobilePhone,
                    "password": userPassword,
                    "message": "invalid loginID or password"
                };

                logger.debug(mobilePhone + ' Failed to login to the system,invalid loginID or password...!');
                res.json(messageUtil.composeFailedMessage(req, '用户名或密码错误'));
                toolUtil.putMessageLoginOrRegisterLogMQ(message);
            }
        }
    })
};

/**
 * 获取用户权限列表
 */
exports.getUserAuthList = function (req, res) {
    var token = req.params.token;

    userService.getUserAuthListService(token, function (err, result) {
        if (err) {
            logger.error('Error happened when getUserAuthList' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            var data = {
                auth: result
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data));
        }
    })
};

/**
 * 第三方登录   1.1.2开始
 */
exports.appThirdPartyLogin = function (req, res) {
    var thirdId = req.params.thirdId;
    var input = req.body;
    var deviceId = req.params.deviceId;

    thirdId = thirdId.toLowerCase();

    userService.appThirdPartyLoginService(thirdId, input, deviceId, function (err, result) {
        if (err) {
            logger.error('Exception happened when login by appThirdPartyLogin...!-' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            var data = result[2];
            data._doc['firstLogin'] = result[1];
            res.json(messageUtil.composeSucceededMessage(req, 'login into the system successfully...', data));
        }
    })
};

/**
 * user-controller.js
 *微信登录
 *author：chenjinzhuan
 * */
exports.loginViaWeChat = function (req, res) {

    var wechatId = req.params.wechatId;
    var input = req.body;
    var clientId = input.clientId;
    logger.debug('login by wechat...');

    userService.loginViaWeChatService(wechatId, input.nickName, input.image, clientId, function (err, user) {
        if (err) {
            logger.error(wechatId + ' Exception happened when login by wechat...!-' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {

            //获取token并缓冲
            var token = toolUtil.generateAndCacheToken(user._id);
            var loginUserData;
            if (user._doc.firstLogin) {
                loginUserData = {
                    "_id": user._id,
                    "token": token,
                    "firstLogin": user._doc.firstLogin,
                    "nickName": user.nickName,
                    "huanxinUserName": user.huanxinUserName,
                    "appSetting": user.appSetting,
                    "userType": user.userType,
                    "images": user.images,
                    "authenticationStatus": user.authenticationStatus
                };
                redisClient.sadd('u:all', user._id);
            } else {
                loginUserData = user;
                user._doc['token'] = token;
                if (user._doc.community != null) {
                    user._doc['communityId'] = user._doc.community._id;
                    user._doc['communityName'] = user._doc.community.communityName;
                }
                user._doc.community = undefined;
                user.frozenOrNot = undefined;
            }
            toolUtil.setUserByToken(token);
            res.json(messageUtil.composeSucceededMessage(req, 'login into the system successfully...', loginUserData));
        }
    })
};


exports.logout = function (req, res) {
    var token = req.params.token;

    userService.logoutService(token, function (err, result) {
        if (err) {
            logger.error('Error happened when logout from the application...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Error happened when logout from the application...!'));
        } else {
            logger.debug('logout from the application...!');
            res.json(messageUtil.composeSucceededMessage(req, 'logged out from the application...', null));
        }
    });
};

/**
 * Find user by User userId
 * userId is the MongoDB id created by the database;
 */
exports.findById = function (req, res) {
    var id = req.params.userId;
    logger.debug('Retrieving a User: ' + id);
    userService.findByIdService(id, function (err, user) {
        if (err) {
            logger.error('Exception happened when trying to find user based on user userId...!');
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when trying to find user based on user userId...!'));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, user));
        }
    });
};

/**
 * User profile update based on the user's userId
 */
exports.updateUser = function (req, res) {

    var token = req.params.token;
    var input = req.body;
    userService.updateService(token, input, function (err, results) {
        if (err) {
            logger.error('Exception happened when trying to update the user data...!' + err.message);
            logger.info(input);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            logger.debug("Update user profile successfully...!");
            res.json(messageUtil.composeSucceededMessage(req, null, null));
            toolUtil.setUserByToken(token);
        }
    })
};


/**
 * 生成验证码
 */
exports.generateVerificationCode = function (req, res) {

    logger.debug("To generate a verificationCode for mobile client...!");
    var deviceId = req.params.deviceId;
    var mobilePhone = req.params.mobilePhone;
    var flag = req.params.flag;
    if (mobilePhone == null) {
        logger.error('Please provide the mobilePhone No....');
        res.json(messageUtil.composeFailedMessage(req, 'Please provide the mobilePhone No....'));
    } else {
        userService.findUserService(mobilePhone, function (err, result) {
            if (err) {
                logger.error('Exception happened when apply to be expert ...!' + err.message);
                res.json(messageUtil.composeFailedMessage(req, ''));
            } else {
                if (flag == 'register') {
                    if (result != null) {
                        res.json(messageUtil.composeFailedMessage(req, '账号已注册请登录'));
                    } else {
                        var message = {
                            "deviceId": deviceId,
                            "mobilePhone": mobilePhone,
                            "verificationCode": toolUtil.generateVerificationCode(mobilePhone, mobilePhone)
                        };
                        toolUtil.putMessageVerificationCodeMQ(message);
                        var tempData = {
                            "verificationCode": message.verificationCode
                        };
                        res.json(messageUtil.composeSucceededMessage(req, null, tempData));
                    }
                } else if (flag == 'forget') {
                    if (result == null) {
                        res.json(messageUtil.composeFailedMessage(req, '您的号码未注册'));
                    } else {
                        var message = {
                            "deviceId": deviceId,
                            "mobilePhone": mobilePhone,
                            "verificationCode": toolUtil.generateVerificationCode(mobilePhone, mobilePhone)
                        };
                        toolUtil.putMessageVerificationCodeMQ(message);
                        var tempData = {
                            "verificationCode": message.verificationCode
                        };
                        res.json(messageUtil.composeSucceededMessage(req, null, tempData));
                    }
                }
            }
        })
    }
};


/**
 * check验证码
 */
exports.checkVerificationCode = function (req, res) {
    logger.debug("To check a verificationCode for mobile client...!");
    var mobilePhone = req.params.mobilePhone;
    var verificationCode = req.params.verificationCode;

    if (mobilePhone != null && verificationCode != null) {
        cacheUtil.cacheGet(mobilePhone, function (err, result) {
            if (result != null && result == verificationCode) {
                logger.debug("Succeeded to check a verificationCode - " + mobilePhone);
                res.json(messageUtil.composeSucceededMessage(req, null, null));
            } else {
                logger.error("Failed to check code ! - invalid verification code!");
                res.json(messageUtil.composeFailedMessage(req, '验证码错误'));
            }
        });
    } else {
        logger.error("Failed to Check verificationCode ! - You have to provide at least mobilePhone +  verificationCode for check...!");
        res.json(messageUtil.composeFailedMessage(req, 'Failed to Check verificationCode ! - You have to provide at least mobilePhone +  verificationCode for check...!'));
    }
};

//验证token
exports.checkToken = function (req, res) {
    var token = req.params.token;

    userService.checkTokenService(token, function (err, results) {
        if (err) {
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            toolUtil.setUserByToken(token);
            var data = results[0];
            data['token'] = token;
            data['auth'] = results[1];
            data['vStatus'] = results[2];
            data['isSignIn'] = results[3];
            res.json(messageUtil.composeSucceededMessage(req, null, data));
        }
    });
};

/**
 * user-controller.js
 *重置密码
 *author：chenjinzhuan
 * */
exports.resetPassword = function (req, res) {
    logger.debug("To reset password....");
    var mobilePhone = req.params.mobilePhone;
    var newPassword = req.params.newPassword;
    userService.resetPasswordService(mobilePhone, newPassword, function (err, results) {
        if (err) {
            logger.error('Exception happened when trying to rest the user password...!');
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when trying to rest the user password...!'));
        } else {
            logger.debug("Reset user password successfully...!");
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    });
};


/**
 * user-controller.js
 *修改密码
 *author：chenjinzhuan
 * */
exports.changePassword = function (req, res) {
    var id = toolUtil.getUserObjIdByToken(req.params.token);
    var userName = req.params.userName;
    var input = req.body;
    logger.debug('Change password.... - ' + id);

    userService.changePaswordService(id, userName, input, function (err) {
        if (err) {
            logger.error('Exception happened when changing password...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            logger.debug("Change password successfully...!");
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    });
};

//========================================================================

/**
 * 设置(上传和修改)个人图像
 * multiPart Body, with a name as "image"
 */

exports.uploadUserProfileImage = function (req, res) {

    var objectName = 'user';
    var token = req.params.token;
    var id = toolUtil.getUserObjIdByToken(token);


    toolUtil.uploadImageService(objectName, id, req, function (err, images) {
        if (err) {
            res.json(messageUtil.composeFailedMessage(req, 'Failed to upload user profile Images... - ' + err.message));
        } else {
            var tempImages = new Array();
            var k = 0;
            for (i = 0; i < images.length; i++) {
                if (images[i] != null)
                    tempImages[k++] = {
                        "imageURL": images[i]
                    }
            }
            userService.setImagesToUser(id, tempImages, function (err, result) {
                if (err || tempImages == null) {
                    res.json(messageUtil.composeFailedMessage(req, 'Failed to upload user profile Images... - ' + err.message));
                } else {
                    res.json(messageUtil.composeSucceededMessage(req, null, null));
                }
            });
        }
    })
}

/**
 * 设置用户小区信息
 * @param req
 * @param res
 */
exports.setUserCommunity = function (req, res) {
    var token = req.params.token;
    var input = req.body;
    var id = toolUtil.getUserObjIdByToken(token);
    userService.setUserCommunityService(token, input, function (err, results) {
        logger.info(results);

        if (err) {
            logger.error('Exception happened when trying to update the user data...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when trying to update the user data...!'));
        } else {
            logger.debug("Update user profile successfully...!");
            var id = {
                "_id": results
            };
            logger.info(id);
            toolUtil.setUserByToken(token);
            res.json(messageUtil.composeSucceededMessage(req, null, id));
        }
    })
};

/**
 * 设置小区新接口  1.1.2
 */
exports.setUserCommunityNew = function (req, res) {
    var token = req.params.token;
    var communityId = req.params.communityId;

    userService.setUserCommunityNewService(token, communityId, function (err, result) {
        if (err) {
            logger.error('Exception happened when trying to setUserCommunityNew...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            var id = {
                "_id": communityId
            };
            toolUtil.setUserByToken(token);
            res.json(messageUtil.composeSucceededMessage(req, null, id));
        }
    })
};

/**
 * user-controller.js
 *获取通讯录
 *author：chenjinzhuan
 * */
exports.getContactList = function (req, res) {
    var id = toolUtil.getUserObjIdByToken(req.params.token);
    logger.debug('Get contactlist.... - ' + id);

    userService.getContactListService(id, function (err, contacts) {
        if (err) {
            logger.error('Exception happened when get contactlist...!');
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when get contactlist...!'));
        } else {
            //将指定id所有的通讯录返回给客户端
            logger.debug("Get contactlist successfully...!");
            res.json(messageUtil.composeSucceededMessage(req, null, contacts));
        }
    });
};

/**
 * user-controller.js
 *添加到通讯录
 *author：chenjinzhuan
 * */
exports.addToContactList = function (req, res) {
    var id = toolUtil.getUserObjIdByToken(req.params.token);
    var userName = req.params.userName;
    var userNameToAdd = req.params.userNameToAdd;
    logger.debug('addToContactList.... - ' + id);

    userService.addToContactListService(id, userName, userNameToAdd, function (err) {
        if (err) {
            logger.error('Exception happened when add to contactList...!');
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when add to contactList...!'));
        } else {
            logger.debug('Add to contactlist successfully...!');
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    });

    //async.waterfall([
    //    //通过用户名获取用户Id
    //    function (callbackInner) {
    //        userService.getUserIdService(userNameToAdd, callbackInner);
    //    },
    //    //将用户添加到通讯录
    //    function (results) {
    //        logger.debug('userId hello:' + results);
    //        userService.addToContactListService(id, results.userId, function (err, results) {
    //            if (err) {
    //                logger.error('Exception happened when add to contactList...!');
    //                res.json(messageUtil.composeFailedMessage(req,'Exception happened when add to contactList...!'));
    //            } else {
    //                logger.debug('Add to contactlist successfully...!');
    //                res.json(messageUtil.composeSucceededMessage(req,null, null));
    //            }
    //        });
    //    }
    //]);


};

/**
 * user-controller.js
 *从通讯录删除
 *author：chenjinzhuan
 * */
exports.RemoveFromContactList = function (req, res) {
    var id = toolUtil.getUserObjIdByToken(req.params.token);
    var userName = req.params.userName;
    var userNameToRemove = req.params.userNameToRemove;
    logger.debug('RemoveFromContactList.... - ' + id);

    userService.RemoveFromContactListService(id, userName, userNameToRemove, function (err) {
        if (err) {
            logger.debug(err.message);
            logger.error('Exception happened when Remove to contactList...!');
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when Remove to contactList...!'));
        } else {
            logger.debug('Remove to contactlist successfully...!');
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    });


    //async.waterfall([
    //    //通过用户名获取用户Id
    //    function (callbackInner) {
    //        userService.getUserIdService(userNameToRemove, callbackInner);
    //    },
    //    //将用户添加到通讯录
    //    function (results) {
    //        //logger.debug('userId hello:' + results);
    //        userService.RemoveFromContactListService(id, results.userId, function (err, results) {
    //            if (err) {
    //                logger.debug(err.message);
    //                logger.error('Exception happened when Remove to contactList...!');
    //                res.json(messageUtil.composeFailedMessage(req,'Exception happened when Remove to contactList...!'));
    //            } else {
    //
    //                //环信删除好友开始
    //                var http = require('http');
    //
    //                //获取环信token
    //                userService.getHuanxinTokenService(function (err, results) {
    //                    if (err) {
    //                        logger.error('Exception happened when remove contactList 1...!');
    //                        res.json(messageUtil.composeFailedMessage(req,'Exception happened when remove contactList 2...!'));
    //                    } else {
    //                        logger.debug('Set Token...!');
    //                        //var resultsParse = JSON.parse(results);
    //                        var resultsParse = results;
    //                        logger.debug('results1: ' + resultsParse);
    //                        logger.debug('results.access_token: ' + resultsParse.access_token);
    //
    //                        //构造链接选项
    //                        var urlOpts = {
    //                            host: 'a1.easemob.com',
    //                            //path: '/easemob-demo/chatdemoui/users/'+userName+'/contacts/users/'+userNameToAdd,
    //                            path: '/66xiaoqu/"+huanxinEnv+"/users/' + userNameToRemove + '/contacts/users/' + userName,
    //                            port: '80',
    //                            method: 'DELETE',
    //                            headers: {
    //                                "Authorization": 'Bearer ' + resultsParse.access_token
    //                            }
    //                        };
    //
    //                        //向环信提交请求
    //                        var request = http.request(urlOpts, function (response) {
    //                            response.on('data', function (chunk) {//请求成功的情况
    //                                logger.debug(chunk.toString());
    //                            });
    //                        }).on('error', function (e) {//请求失败的情况
    //                            logger.debug('error:' + e.stack);
    //                            //添加已经删除的数据库中的好友
    //                            userService.addToContactListService(id, idToRemove, function (err) {
    //                                if (err) {
    //                                    logger.debug(err.message);
    //                                    logger.error('Exception happened when add to contactList in RemoveFromContactList...!');
    //                                    res.json(messageUtil.composeFailedMessage(req,'Exception happened when add to contactList in RemoveFromContactList...!'));
    //                                } else {
    //                                    logger.debug('Add to contactlist successfully in RemoveFromContactList...!');
    //                                }
    //                            });
    //                        });
    //                        // write data to request body
    //                        //request.write(post_data + "\n");
    //                        request.end();
    //                    }
    //                });
    //
    //                //环信删除好友结束
    //
    //                logger.debug('Remove to contactlist successfully...!');
    //                res.json(messageUtil.composeSucceededMessage(req,null, null));
    //            }
    //        });
    //    }
    //]);


};

/**
 * 关注
 */
exports.followup = function (req, res) {
    var category = req.params.category;
    var token = req.params.token;
    var id = req.params.id;

    userService.followupService(category, token, id, function (err, result) {
        if (err) {
            logger.error('Exception happened when followup a question or activity ...!' + err.message + id);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            var followId = {
                "_id": result._id
            };
            res.json(messageUtil.composeSucceededMessage(req, null, followId));
        }
    })
};

/**
 * 取消关注
 */
exports.cancelFollowup = function (req, res) {
    var category = req.params.category;
    var token = req.params.token;
    var id = req.params.id;

    userService.cancelFollowupService(category, token, id, function (err, result) {
        if (err) {
            logger.error('Exception happened when cancel followup a question or activity ...!' + err.message + id);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    })
};

/**
 * 获取某类关注清单
 */
exports.getFollowupList = function (req, res) {
    var category = req.params.category;
    var token = req.params.token;
    var page = req.params.pageNo;

    userService.getFollowupListService(page, category, token, function (err, results) {
        if (err) {
            logger.error('Exception happened when get followupList ...!' + token);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when get followupList...!'));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, results));
        }
    });
};

exports.getNeighbourList = function (req, res) {
    var token = req.params.token;
    var page = req.params.pageNo;
    userService.getNeighbourListService(page, token, function (err, results) {
        if (err) {
            logger.error('Exception happened when get neighbour list ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when get neighbour list...!'));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, results));
        }
    })
}

exports.applyToBeExpert = function (req, res) {
    var token = req.params.token;
    var input = req.body;

    userService.applyToBeExpertService(token, input, function (err, result) {
        if (err) {
            logger.error('Exception happened when apply to be expert ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when apply to be expert...!' + err.message));
        } else {
            var msg = '已提交申请，请等候审核结果';

            res.json(messageUtil.composeSucceededMessage(req, msg, null));
        }
    })
};

exports.findUser = function (req, res) {
    var id = req.params.id;

    userService.findUserService(id, function (err, result) {
        if (err) {
            logger.error('Exception happened when apply to be expert ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, ''));
        } else {
            if (result == null) {
                res.json(messageUtil.composeFailedMessage(req, '用户不存在'));
            } else {
                res.json(messageUtil.composeSucceededMessage(req, null, null));
            }
        }
    })
};

exports.getUserProfile = function (req, res) {
    var userId = req.params.userId;
    var token = req.params.token;
    userService.getUserProfileService(userId, token, function (err, results) {
        if (err) {
            logger.error('Exception happened when get user profile by userId ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            var data = {
                "isFollowup": results[3],
                "profile": results[1],
                "question": results[2]
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data));
        }
    })
};

/**
 * 获取用户问题列表
 */
exports.getUserQuestionList = function (req, res) {
    var userId = req.params.userId;
    var pageNo = req.params.pageNo;
    var token = req.params.token;
    userService.getUserQuestionListService(pageNo, userId, token, function (err, results) {
        if (err) {
            logger.error('Exception happened when get user question list by userId ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when get user question list by userId ...!'));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, results));
        }
    })
};

exports.getUserQuestionListNew = function (req, res) {
    var userId = req.params.userId;
    var pageNo = req.params.pageNo;
    var token = req.params.token;

    userService.getUserQuestionListNewService(pageNo, userId, token, function (err, results) {
        if (err) {
            logger.error('Exception happened when getUserQuestionListNew ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, results));
        }
    })
};

exports.getHomePage = function (req, res) {
    var token = req.params.token;

    userService.getHomePageService(token, function (err, results) {
        if (err) {
            logger.error('Exception happened when get home page ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {

            var data = {
                "modules": results[0],
                "news": results[1],
                "question": results[2],
                "special": results[3],
                "talent": results[4]
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data));
        }
    })
};

exports.homePageBanner = function (req, res) {
    var token = req.params.token;

    userService.homePageBannerService(token, function (err, result) {
        if (err) {
            logger.error('Exception happened when get homePageBanner' + err.message);
            res.json(messageUtil.composeErrorMessage(req, err))
        } else {
            var data = {
                banner: result
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data));
        }
    })
};

exports.homePageFreshNews = function (req, res) {
    var token = req.params.token;

    userService.homePageFreshNewsService(token, function (err, result) {
        if (err) {
            logger.error('Exception happened when get homePageFreshNewsService' + err.message);
            res.json(messageUtil.composeErrorMessage(req, err))
        } else {
            var data = {
                freshNews: result
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data));
        }
    })
};

exports.homePageQuestionAndActivity = function (req, res) {
    var token = req.params.token;

    userService.homePageQuestionAndActivityService(token, function (err, result) {
        if (err) {
            logger.error('Exception happened when get homePageQuestionAndActivity' + err.message);
            res.json(messageUtil.composeErrorMessage(req, err))
        } else {
            var data = {
                questions: result[0],
                activities: result[1]
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data));
        }
    })
};

exports.homePageTopics = function (req, res) {
    var token = req.params.token;

    userService.homePageTopicsService(token, function (err, result) {
        if (err) {
            logger.error('Exception happened when get homePageTopics' + err.message);
            res.json(messageUtil.composeErrorMessage(req, err))
        } else {
            var data = {
                topics: result
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data));
        }
    })
};

exports.userSignIn = function (req, res) {
    var token = req.params.token;

    userService.userSignInService(token, function (err, result) {
        if (err) {
            logger.error('Exception happened when get userSignIn' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message))
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, {signInValue: signInValue}));
        }
    })
};

//随便逛逛
exports.randomSetCommunity = function (req, res) {
    var token = req.params.token;

    userService.randomSetCommunityService(token, function (err, result) {
        var id = {
            "_id": result
        };
        toolUtil.setUserByToken(token);
        res.json(messageUtil.composeSucceededMessage(req, null, id));
    })
};


exports.getUserQuestionStatistics = function (req, res) {
    var token = req.params.token;
    var userId = req.params.userId;

    userService.getUserQuestionStatisticsService(token, userId, function (err, result) {
        if (err) {
            logger.error('Exception happened when getUserQuestionStatistics ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            var data = {
                "questionCount": result[0],
                "replyCount": result[1],
                "adoptRate": result[2],
                "praised": result[3]
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data));
        }
    })
};

exports.getFollowupUsers = function (req, res) {
    var token = req.params.token;

    userService.getFollowupUsersService(token, function (err, result) {
        if (err) {
            logger.error('Exception happened when getFollowupUsers ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    });
};

/**
 * 用户认证
 * @param req
 * @param res
 */
exports.authenticateUser = function (req, res) {
    var token = req.params.token;
    var invitationCode = req.body.invitationCode;
    var deviceId = req.params.deviceId;

    if (invitationCode != null && invitationCode != '') {
        userService.validateInvitationCodeService(token, invitationCode, function (err, user) {
            if (err) {
                logger.error('Exception happened when authenticateUser ...!' + err.message);
                res.json(messageUtil.composeFailedMessage(req, err.message));
            } else {
                userService.authenticateUserService(token, req, function (err, result) {
                    if (err) {
                        logger.error('Exception happened when authenticateUser ...!' + err.message);
                        res.json(messageUtil.composeFailedMessage(req, err.message));
                    } else {
                        res.json(messageUtil.composeSucceededMessage(req, '已提交资料，请等待审核', null));
                        //绑定邀请关系
                        userService.bindInvitationCodeService(token, user, invitationCode, deviceId);
                    }
                });
            }
        })
    } else {
        userService.authenticateUserService(token, req, function (err, result) {
            if (err) {
                logger.error('Exception happened when authenticateUser ...!' + err.message);
                res.json(messageUtil.composeFailedMessage(req, err.message));
            } else {
                res.json(messageUtil.composeSucceededMessage(req, '已提交资料，请等待审核', null));
            }
        });
    }
};

exports.authenticateUserByPromotionCode = function (req, res) {
    var code = req.body.code;
    var token = req.params.token;
    var invitationCode;

    if (invitationCode != null && invitationCode != '') {
        userService.validateInvitationCodeService(token, invitationCode, function (err, user) {
            if (err) {
                logger.error('Exception happened when authenticateUserByPromotionCode ...!' + err.message);
                res.json(messageUtil.composeFailedMessage(req, err.message));
            } else {
                userService.authenticateUserByPromotionCodeService(code, token, function (err, result) {
                    if (err) {
                        logger.error('Exception happened when authenticateUserByPromotionCode' + err.message);
                        res.json(messageUtil.composeFailedMessage(req, err.message));
                    } else {
                        res.json(messageUtil.composeSucceededMessage(req, null, result[3]));
                        exports.authenticationAddScore(token);

                        //绑定邀请关系
                        userService.bindInvitationCodeService(token, user);

                        //邀请人加分
                        mysqlUtil.generateUserVoucher(user._id, 2, token, function (err, result) {
                            if (err) logger.error(err.message);
                        });
                    }
                })
            }
        });
    } else {
        userService.authenticateUserByPromotionCodeService(code, token, function (err, result) {
            if (err) {
                logger.error('Exception happened when authenticateUserByPromotionCode' + err.message);
                res.json(messageUtil.composeFailedMessage(req, err.message));
            } else {
                res.json(messageUtil.composeSucceededMessage(req, null, result[3]));

                exports.authenticationAddScore(token);
            }
        })
    }
};

exports.getUserAuthenticationStatus = function (req, res) {
    var token = req.params.token;
    userService.getUserAuthenticationStatusService(token, function (err, result) {
        if (err) {
            logger.error('Exception happened when getUserAuthenticationStatusService ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    });
};


exports.authenticationAddScore = function (token) {

    userDevice.findOne({userId: token}, 'vCode', function (err, version) {
        if ((version != null && version.vCode != null && version.vCode < 1403) || enbaleVoucher == 'No') {
            var arg = {
                userId: token,
                userRole: 1,
                userActionType: 1
            };

            arg.__type__ = 'com.neighborhoods.service.score.dto.ScoreAddRequestDto';

            scoreProxy.invoke('addScore', [arg], function (err, reply) {
                try {
                    var data = JSON.parse(decodeURIComponent(reply));
                    if (err) {
                        logger.error('hessianInvokeAddScore-----' + err.message);
                    } else if (data.status != 0) {
                        logger.error('hessianInvokeAddScore----' + data.status + '----' + data.msg);
                    }
                } catch (e) {
                    logger.error('hessianInvokeAddScore---' + e);
                }
            });
        } else {
            Users.findOne({_id: token}, function (err, user) {
                if (user == null || user.community == null) {
                    logger.error('无效用户')
                } else {
                    mysqlUtil.query('select * from voucher_user_bind where user_id=? and reward_source=1', [user._id + ''], function (err, result) {
                        if (err || result.length > 0) {
                            if (err)logger.error(err.message);
                            logger.error('v认证无法重复增加奖励')
                        } else {

                            inviteRecord.findOne({
                                user: user._id + '',
                                source: 1
                            }, function (err, invite) {
                                if (invite != null) {
                                    logger.error('已有情值奖励，无法重复增加奖励')
                                } else {
                                    var community = user.community + '';
                                    var nowDate = new Date().getTime();
                                    var sql = 'select voucher_type_id,reward_expiredate_length,type,voucher_val,community_name from voucher_reward_rule r,voucher_type t where r.from_time<? and r.to_time>? and r.reward_source=? and r.community_id=? and t.id=r.voucher_type_id';
                                    mysqlUtil.query(sql, [nowDate, nowDate, 1, community], function (err, result) {
                                        if (err || result.length == 0) {
                                            logger.error(err ? err : '无奖励规则');
                                        } else {
                                            if (result[0].type == 1) {
                                                mysqlUtil.getCardNumber(function (number) {
                                                    var cardNo = moment().format('YYMMDD') + number;
                                                    var expire = moment(nowDate).endOf('day').toDate().getTime() + result[0].reward_expiredate_length * 24 * 60 * 60 * 1000;
                                                    var data = {
                                                        user_id: user._id + '',
                                                        expire_time: expire,
                                                        voucher_type_id: result[0].voucher_type_id,
                                                        is_use: 0,
                                                        reward_source: 1,
                                                        card_no: cardNo,
                                                        community_name: result[0].community_name,
                                                        create_time: new Date().getTime()
                                                    };
                                                    mysqlUtil.query('insert into voucher_user_bind set?', data, function (err, result) {
                                                        if (err) {
                                                            logger.error(err);
                                                        } else {
                                                            var content = {
                                                                type: 1,
                                                                flag: 2,
                                                                openType: 8,
                                                                contentId: user._id,
                                                                desc: '恭喜您！您获得了一张代金券'
                                                            };
                                                            var pushData = {
                                                                uList: [user._id],
                                                                content: content,
                                                                tag: '福利券',
                                                                type: 'operate'
                                                            };
                                                            toolUtil.putMessageGetuiPushMQ(pushData);
                                                        }
                                                    })
                                                });
                                            } else if (result[0].type == 2) {
                                                var input = {
                                                    userId: user._id + '',
                                                    scoreAddCount: result[0].voucher_val,
                                                    scoreAddRason: 'V认证'
                                                };

                                                logger.info(input);

                                                input.__type__ = 'com.neighborhoods.service.score.dto.ScoreAddRequestDto';

                                                scoreProxy.invoke('addScoreManual', [input], function (err, result) {
                                                    if (err) {
                                                        logger.error('Exception happened when addScoreManual ...!' + err.message);
                                                        callback();
                                                    } else {
                                                        var data = JSON.parse(decodeURIComponent(result));
                                                        logger.info(data);
                                                        if (data.status == 0) {
                                                            var temp = new inviteRecord();
                                                            temp.user = user._id + '';
                                                            temp.source = 1;
                                                            temp.score = input.scoreAddCount;
                                                            temp.reason = input.scoreAddRason;
                                                            temp.save();

                                                        }
                                                    }
                                                });
                                            }
                                        }
                                    });
                                }
                            });
                        }
                    });
                }
            })
        }
    });
};

exports.getUserInvitedCode = function (req, res) {
    var token = req.params.token;

    userService.getUserInvitedCodeService(token, function (err, result) {
        var data = {
            invitedCode: result,
            invitedAuth: 0
        };
        res.json(messageUtil.composeSucceededMessage(req, null, data))
    });
};


exports.getMyVoucherList = function (req, res) {
    var token = req.params.token;

    userService.getMyVoucherListService(token, function (err, result) {
        if (err) {
            logger.error('Exception happened when getMyVoucherList ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {

            var data = {
                voucherList: result
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data));
        }
    })
};

exports.getVoucherDetail = function (req, res) {
    var voucherId = req.params.voucherId;
    var token = req.params.token;

    userService.getVoucherDetailService(Number(voucherId), token, function (err, result) {
        if (err) {
            logger.error('Exception happened when getVoucherDetail ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            var data = {
                voucher: result[0],
                retailerList: result[1]
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data));
        }
    })
}

//=================================================== Web后台管理 ============================================

//根据查询条件，页码显示用户
exports.findByNameORPhone = function (req, res) {
    var pageNo = req.params.pageNo;
    var input = req.body;

    userService.findByNameORPhoneService(pageNo, input, function (err, result) {
        if (err) {
            logger.error('Exception happened when apply to be expert ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, ''));
        } else {
            if (result == null) {
                res.json(messageUtil.composeFailedMessage(req, '没有用户'));
            } else {
                res.json(messageUtil.composeSucceededMessage(req, null, result));
            }
        }
    })
};

//根据页码显示全部用户
exports.getAllUser = function (req, res) {
    var pageNo = req.params.pageNo;

    userService.getAllUserService(pageNo, function (err, result) {
        if (err) {
            logger.error('Exception happened when apply to be expert ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, ''));
        } else {
            if (result == null) {
                res.json(messageUtil.composeFailedMessage(req, '没有用户'));
            } else {
                res.json(messageUtil.composeSucceededMessage(req, null, result));
            }
        }
    })
};

/**
 * 后台注册用户
 */
exports.registerUserFromBackOffice = function (req, res) {
    var input = req.body;
    var errorMsg = '';
    var successMsg = '';
    for (var i = 0; i < input.length; i++) {
        if ((input[i].userName != null || input[i].email != null || input[i].mobilePhone != null) && input[i].userPassword != null) {
            userService.registerUserFromBackOfficeService(input[i], function (err, user) {
                if (err) {
                    logger.error("Failed to register this user - " + err.message);
                    errorMsg = errorMsg + JSON.stringify(input[i]) + ',';
                } else {
                    logger.debug("Succeeded to register a user! - " + user._id);
                    //获取token并缓冲
                    logger.info(user._id);
                    var token = toolUtil.generateAndCacheToken(user._id);
                    //返回消息
                    var registerUserData = {
                        "_id": user._id,
                        "huanxinUserName": user.huanxinUserName,
                        "token": token
                    };
                    //userService.sendWelcomeNewsService(input.mobilePhone, function (err, result) {
                    //    if (err) {
                    //        logger.error('failed to send welcome news' + err.message);
                    //    }
                    //});
                    successMsg = successMsg + JSON.stringify(input[i]) + ',';
                }
                if (i == input.length - 1) {
                    //fix me : 应该在全部添加完成时回调方法里面加
                    logger(errorMsg + '  ' + successMsg);
                    res.json(messageUtil.composeSucceededMessage(req, errorMsg + '创建失败\n' + successMsg + '创建成功', null));
                }
            });
        }
        else {
            logger.error("Failed to register user ! - You have to provide at least userID/email/mobilePhone and also password for registration...!");
            errorMsg = errorMsg + JSON.stringify(input[i]) + ',';
            if (i == input.length - 1) {
                //fix me : 应该在全部添加完成时回调方法里面加
                res.json(messageUtil.composeSucceededMessage(req, errorMsg + '创建失败\n' + successMsg + '创建成功', null));
            }
        }
    }
};


/**
 * user-controller.js
 *搜索用户
 *author：chenjinzhuan
 * */
exports.searchBackOfficeUser = function (req, res) {
    //var pageNo = req.params.pageNo;
    var input = req.body;

    userService.searchBackOfficeUserService(input, function (err, result) {
        if (err) {
            logger.error('Exception happened when apply to be expert ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, ''));
        } else {
            if (result == null) {
                res.json(messageUtil.composeFailedMessage(req, '没有用户'));
            } else {
                res.json(messageUtil.composeSucceededMessage(req, null, result));
            }
        }
    })
};

/**
 * user-controller.js
 * 登录验证
 *author：chenjinzhuan
 * */
exports.adminLogin = function (req, res) {
    var input = req.body;

    userService.adminLoginService(input, function (err, result) {
        if (err) {
            logger.error('Exception happened when login ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when login ...!' + err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    })
};

exports.getAuthenticationUserList = function (req, res) {
    var communityId = req.params.communityId;
    var status = req.params.status;
    var nickname = req.params.nickname;
    var page = req.params.page;

    userService.getAuthenticationUserListService(communityId, status, nickname, page, function (err, result) {
        if (err) {
            logger.error('Exception happened when getAuthenticationUserList ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when getAuthenticationUserList ...!' + err.message));
        } else {
            var data = {
                uList: result[0],
                totalPage: Math.ceil(result[1] / 20)
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data));
        }
    })
}

/**
 * 审核用户认证
 * @param req
 * @param res
 */
exports.examineUserAuthenticate = function (req, res) {
    var body = req.body;

    userService.examineUserAuthenticateService(body, function (err, result) {
        if (err) {
            logger.error('Exception happened when examineUserAuthenticate ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
            if (body.status) {
                exports.authenticationAddScore(body.user);

                if (result[1] != null) {

                    mysqlUtil.generateUserVoucher(result[1], 2, body.user, function (err, voucher) {
                        if (err) {
                            logger.error(err.message);
                        } else {
                            userInvitation.update({invitee: body.user}, {
                                score: voucher.value,
                                dateLastModified: new Date(),
                                type: voucher.type
                            }).exec();

                            //放入周排行榜
                            var key = 'rank:invitation:' + moment().startOf('isoWeek').format('YYYYMMDD');
                            redisClient.ZINCRBY(key, 1, result[1]);

                            //放入总排行榜
                            var totalKey = 'rank:invitation:total';
                            redisClient.ZINCRBY(totalKey, 1, result[1]);
                        }
                    });


                    var message = {
                        msgType: 'invite',
                        userId: result[1],
                        inviteUserId: body.user
                    };
                    toolUtil.putMessageBusinessMQ(message);

                    //建立相互关注
                    backUserService.eachOtherFollowupService(body.user + '', result[1] + '');
                }
            }
        }
    })


};

exports.refuseUserAuthenticate = function (req, res) {
    var id = req.params.id;
    var body = req.body;

    userService.refuseUserAuthenticateService(id, body, function (err, result) {
        if (err) {
            logger.error('Exception happened when refuseUserAuthenticate ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when refuseUserAuthenticate ...!' + err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    })
};

exports.generateVoucher = function (req, res) {
    var userId = req.params.userId;

    mysqlUtil.generateUserVoucher(userId, 2, '549968e5bc537bb017000a04', function (err, result) {
        if (err) {
            logger.error(err);
        }
        res.json({message: 1})
    })
};

exports.getRecentContactPerson = function (req, res) {
    var token = req.params.token;

    userService.getRecentContactPersonService(token, function (err, result) {
        if (err) {
            logger.error('Exception happened when getRecentContactPerson ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            var data = {
                users: result
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data));
        }
    })
};

exports.getScoreRank = function (req, res) {
    var pageNo = req.params.pageNo;
    var token = req.params.token;

    userService.getScoreRank(token, pageNo, function (err, result) {
        if (err) {
            logger.error('Exception happened when getScoreRank ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            var data = {
                rankList: result
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data));
        }
    })
};
